'use strict';
const Service = require('egg').Service
const uuid = require('uuid')
const moment = require('moment')
const TOKEN_DIFF = 60 * 60 * 1000

class LoginService extends Service {
  async doLogin({ username, password }) {
    const { ajaxReturn, ajaxCode } = this.ctx.helper
    if (!username || !password) {
      return ajaxReturn(null, { ...ajaxCode.PARAMS_ERROR })
    }
    const { User, Role, UserToken } = this.app.model
    console.log('user', Object.keys(new User()))
    let include = [{ model: Role, attributes: ['name'] }]
    let result = await User.findOne({
      include,
      where: { username, password },
      attributes: User.allKeys.filter(_ => !['password', 'role_id'].includes(_))
    })
    if (!result) {
      return ajaxReturn(result, Object.assign({ ...ajaxCode.NO_DATA_ERROR }, { msg: '账号或密码错误' }) )
    }
    const { id: user_id } = result
    const token = uuid.v1()
    const update_at = Date.now()
    let t = await UserToken.create({ user_id, token, update_at })
    return ajaxReturn({
      user: result.toJson(),
      token: t.token
    })
  }
  async getUserByToken({ token }) {
    const {ajaxReturn, ajaxCode} = this.ctx.helper
    const { UserToken, User, Role } = this.app.model
    if (!token) {
      return ajaxReturn(null, {...ajaxCode.PARAMS_ERROR})
    }

    const include = [{
      model: User,
      include: [{ model: Role, attributes: ['name'] }],
      attributes: User.allKeys.filter(_ => !['password', 'role_id'].includes(_))
    }]
    let result = await UserToken.findOne({
      include,
      where: { token }
    })
    if (!result) {
      return ajaxReturn(result, Object.assign({ ...ajaxCode.NO_DATA_ERROR }, { msg: '账号或密码错误' }) )
    }
    console.log('2', Date.now() - result.update_at)
    // console.log('3', Date.now())
    // console.log('4', moment.now())
    // await result.update({update_at: Date.now()})
    if (Date.now() - result.update_at > TOKEN_DIFF) {
      return ajaxReturn(null, Object.assign({...ajaxCode.OTHER_ERROR}, { msg: 'token 过期' }))
    }
    return ajaxReturn(result.toJson())
  }

}
module.exports = LoginService